package br.edu.ufersa.scrumgame.mbean;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import br.edu.ufersa.scrumgame.facade.JogadorFacade;
import br.edu.ufersa.scrumgame.modelo.Jogador;

@ManagedBean
@SessionScoped
public class SessaoMBean {
	
	@EJB
	private JogadorFacade jogadorFacade;
	
	private List<Jogador> jogadoresOnline;
	
	public JogadorFacade getJogadorFacade() {
		return jogadorFacade;
	}

	public void setJogadorFacade(JogadorFacade jogadorFacade) {
		this.jogadorFacade = jogadorFacade;
	}

	public List<Jogador> getJogadoresOnline() {
		getAllSession();
		return jogadoresOnline;
	}

	public void setJogadoresOnline(List<Jogador> jogadoresOnline) {
		this.jogadoresOnline = jogadoresOnline;
	}

	public boolean showSair() {
		
		boolean retorno = false;

		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		
		if(authentication != null && !authentication.getPrincipal().equals("anonymousUser")) {
			retorno = true;
		}

		return retorno;
	}
	
	public boolean showAdmin() {
		
		boolean isAdmin = false;

		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		for( GrantedAuthority ga : authentication.getAuthorities() ) {
			if(ga.getAuthority().equals("ADMIN")) {
				isAdmin = true;
				break;
			}
		}

		return isAdmin;
	}

	public List<Jogador> getAllSession() {

		WebApplicationContext wc = ContextLoader.getCurrentWebApplicationContext();
		
		SessionRegistry sessionRegistry = (SessionRegistry) wc.getBean("sessionRegistry");
		List<Object> principals = sessionRegistry.getAllPrincipals();
		jogadoresOnline = new ArrayList<Jogador>();
		for(Object i : principals) {
			if( i instanceof User ) {
				jogadoresOnline.add( jogadorFacade.findUsuarioByEmail(((User) i).getUsername()));
			}
		}

		return jogadoresOnline;
		
	}
	
	public String getUserSession() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		
		return authentication.getName();
	}

}
